﻿﻿var apiFrameUrl = GetRootPath();
var homeUrl = "http://localhost/ZhaoTouBiao/index.html"
var tokenid = "hpframetokenid";
var tokenModel = "hpframetokenModel";

var CookieUserName = "hpframe_username";
var Cookiepassword = "hpframe_password";


$(function () {
    //控制手风琴样式
    $(".accordion_hide").hide();

    $(".accordion_title_arrow_bottom,.accordion_title_arrow_right").click(function () {
        var accordion_content = $(this).parent().parent().parent().find('.accordion_content');
        if (accordion_content.hasClass("accordion_hide")) {
            $(this).removeClass("accordion_title_arrow_right");
            $(this).addClass("accordion_title_arrow_bottom");
            accordion_content.removeClass("accordion_hide");
            accordion_content.show();
        } else {
            $(this).addClass("accordion_title_arrow_right");
            $(this).removeClass("accordion_title_arrow_bottom");
            accordion_content.addClass("accordion_hide");
            accordion_content.hide();
        }
    });
})

function getheadinfo() {
    return {
        "Content-Type": "application/json;charset=uft-8"
        // "token": GetTokenID(),
        // "timestamp": new Date().getTime(),
        // "deviceid": "",
        // "os": "",
        // "sign": hex_md5("" + "" + new Date().getTime() + GetTokenID()),
    };
}

function gettokenparams_urlformat() {
    var token = GetTokenID()
    var timestamp = new Date().getTime()
    var deviceid = "";
    var os = "";
    var sign = hex_md5(deviceid + os + new Date().getTime() + token);
    return "token=" + token + "&timestamp=" + timestamp + "&deviceid=" + deviceid + "&os=" + os + "&sign=" + sign;
}

function gettokenparams_jsonformat(exjson) {
    var headinfo = {
        "token": GetTokenID(),
        "timestamp": new Date().getTime(),
        "deviceid": "",
        "os": "",
        "sign": hex_md5("" + "" + new Date().getTime() + GetTokenID()),
    }
    if (exjson) {
        for (var obj in exjson) {
            headinfo[obj] = exjson[obj];
        }
    }
    return headinfo;

}

function getDefalutlayout() {

    return "total, sizes, prev, pager, next, jumper";
}

function getpageSize(pageSize) {
    //if (pageSize == 0) {
    //    var CH = document.documentElement.clientHeight;
    //    pageSize = CH >= 1000 ? 20 : (CH >= 800 ? 15 : 10);
    //}
    return pageSize;
}

function checkUserInfo() {
    if (localStorage.getItem("local_tokendate") == null) {
        window.top.location.href = GetRootPath() + "page/home/login.html";
    }
}

function CaltableHeight(cutHeight, searchH, footH) {
    var cutH = 79;
    if (typeof cutHeight != undefined)
        cutH = cutHeight;

    var tH = document.documentElement.clientHeight - (footH || 32) - (searchH || 60) - cutH;

    //console.log("document.documentElement.clientHeight:" + document.documentElement.clientHeight + "; footH:" + footH + "; searchH:" + searchH + "; cutH:" + cutH);

    //console.log("footH:" +  (footH || 32));
    //console.log("searchH:" + (searchH || 60));
    //console.log("cutH:" + cutH);
    //console.log("tH" + tH);

    return tH;
}


/********************token 开始 */
function GetTokenID() {
    return localStorage.getItem(tokenid);
}

function GetTokenModel() {
    return localStorage.getItem(tokenModel);
}

function SetTokenID(UserTokenID) {
    localStorage.setItem(tokenid, UserTokenID);
}

function SetTokenModel(UserTokenModel) {
    localStorage.setItem(tokenModel, UserTokenModel);
}
/********************token 结束 */

function RemoeToken() {
    localStorage.removeItem('tokenid');
    localStorage.removeItem('tokenModel');
}



function getRootPath_OnlyVirName() {
    var strFullPath = window.document.location.href;
    var strPath = window.document.location.pathname;
    var pos = strFullPath.indexOf(strPath);
    var prePath = strFullPath.substring(0, pos);
    var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
    return postPath;
}

//获取URL参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var Url = window.location.href;

    if (Url.indexOf("?") > 0)
        Url = "&" + Url.substr(Url.indexOf("?") + 1);

    var r = Url.match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]);
    return ''; //返回参数值
}


function getUrlParamGroup() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

function getUrlParamGroupString() {
    var url = location.search; //获取url中"?"符后的字串
    if (url.indexOf("?") != -1) {
        return url.substr(1);
    } else {
        return "";
    }
}

function HandleUrlRandom(Url) {
    if (Url.indexOf("?") < 0)
        Url = Url + "?t=" + Math.random();
    else
        Url = Url + "&t=" + Math.random();
    return Url;
}

function handleUrlAndParams(targetUrl) {
    var paramstring = getUrlParamGroupString();
    if (targetUrl.indexOf("?") < 0) {
        targetUrl = targetUrl + "?" + paramstring;
    } else {
        targetUrl = targetUrl + "&" + paramstring;
    }
    return targetUrl;
}

//根据attachguid获取附件下载地址
function getAttachReadUrl(attguid) {
    return apiFrameUrl + "/common/attachment/readFile?attguid=" +
        attguid;
}

function JsonAjax(JsonData, Url, SucessFunctionName) {
    if (Url.indexOf("?") < 0)
        Url = Url + "?t=" + Math.random();
    else
        Url = Url + "&t=" + Math.random();

    $.ajax({
        url: Url,
        type: "POST",
        headers: getheadinfo(),
        data: JsonData,
        dataType: 'json',
        complete: function () {},
        success: SucessFunctionName,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //var strLog = "详细错误：" + XMLHttpRequest.responseText;                //writeFile("c:\\qd.log", strLog);
            ///alert(errorThrown + ";详细错误：" + XMLHttpRequest.responseText);
        }
    });
}


function JsonAjaxFormData(JsonData, Url, SucessFunctionName) {
    if (Url.indexOf("?") < 0)
        Url = Url + "?t=" + Math.random();
    else
        Url = Url + "&t=" + Math.random();

    $.ajax({
        url: Url,
        type: "POST",
        contentType: false,
        // 告诉jQuery不要去设置Content-Type请求头
        processData: false,
        // 告诉jQuery不要去处理发送的数据
        data: JsonData,
        dataType: 'json',
        complete: function () {},
        success: SucessFunctionName,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //var strLog = "详细错误：" + XMLHttpRequest.responseText;                //writeFile("c:\\qd.log", strLog);
            ///alert(errorThrown + ";详细错误：" + XMLHttpRequest.responseText);
        }
    });
}

function JsonAjax_Sync(JsonData, Url, SucessFunctionName) {
    if (Url.indexOf("?") < 0)
        Url = Url + "?t=" + Math.random();
    else
        Url = Url + "&t=" + Math.random();

    $.ajax({
        async: false,
        url: Url,
        type: "POST",
        headers: getheadinfo(),
        data: JsonData,
        dataType: 'json',
        complete: function () {},
        success: SucessFunctionName,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //var strLog = "详细错误：" + XMLHttpRequest.responseText;                //writeFile("c:\\qd.log", strLog);
            ///alert(errorThrown + ";详细错误：" + XMLHttpRequest.responseText);
        }
    });
}

function FormAjax(FormData, Url, SucessFunctionName) {
    if (Url.indexOf("?") < 0)
        Url = Url + "?t=" + Math.random();
    else
        Url = Url + "&t=" + Math.random();

    $.ajax({
        url: Url,
        type: "POST",
        headers: gettokenparams_jsonformat(),
        data: FormData,
        dataType: 'JSON',
        cache: false, // 不缓存
        processData: false, // jQuery不要去处理发送的数据
        contentType: false, // jQuery不要去设置Content-Type请求头
        complete: function () {},
        success: SucessFunctionName,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //var strLog = "详细错误：" + XMLHttpRequest.responseText;                //writeFile("c:\\qd.log", strLog);
            ///alert(errorThrown + ";详细错误：" + XMLHttpRequest.responseText);
        }
    });
}

function OpenMaxWin(url) {
    window.open(url, '_blank', 'channelmode=no,directories=no,fullscreen=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,titlebar=yes,toolbar=no,left=' + (screen.availWidth < '+width+' ? 0 : (screen.availWidth - '+width+') / 2) + ',top=' + (screen.availHeight < '+height+' ? 0 : (screen.availHeight - '+height+') / 2) + ',width=' + screen.availWidth + ',height=' + screen.availHeight);
}

var searchtoolbarheight = 60;
var opbuttonbarheight = 60;
//这里的5px是分页控件的样式margin-top，这里要加上，否则使用模态窗口打开列表页面会有滚动条
//ypeng 20200101
var paginationheight = 32 + 5

function getStandTableHeight() {
    return document.body.clientHeight - searchtoolbarheight - opbuttonbarheight - paginationheight;
}

//获取代码项
function bindDMPCode(codeName, callback) {
    var codeItemUrl = apiFrameUrl + "/ZhaoTouBiao/Common.ashx?method=getcode";
    var data = {
        "cname": codeName
    }
    JsonAjax_Sync(JSON.stringify(data), codeItemUrl, function (result, status) {
        if (callback) {
            callback(result, status);
        }
    })
}

//生成uuid
function getNewGuid() {
    var date = new Date();
    var dateGuid = convertDateToString(date);
    return dateGuid + Math.ceil(Math.random()*1000);
}

function convertDateToString(now) {
    var year = now.getFullYear();
    var month = (now.getMonth() + 1).toString();
    var day = (now.getDate()).toString();
    var hour = (now.getHours()).toString();
    var minute = (now.getMinutes()).toString();
    var second = (now.getSeconds()).toString();
    if (month.length == 1) {
        month = "0" + month;
    }
    if (day.length == 1) {
        day = "0" + day;
    }
    if (hour.length == 1) {
        hour = "0" + hour;
    }
    if (minute.length == 1) {
        minute = "0" + minute;
    }
    if (second.length == 1) {
        second = "0" + second;
    }
    var dateTime = year + month + day + hour + minute + second;
    return dateTime;
}

function startLoading(context, loadingText) {
    var loadOption = {
        lock: true,
        text: '加载中',
    }
    if (loadingText) {
        loadOption.text = loadingText;
    }
    const loading = context.$loading(loadOption);
    return loading;
}

function getPageSize() {
    var CH = document.documentElement.clientHeight;
    return CH >= 1000 ? 20 : (CH >= 800 ? 15 : 10);
}

function setLocalData(key, value) {
    localStorage.setItem(key, value);
}

function getLocalData(key) {
    return localStorage.getItem(key);
}


//上传文件及订单数据结构部分
var uploadFileDataID = "fastprint_uploadfiledata";
var printOrderDataID = "fastprint_printorderdata";

function refreshUploadFileData(groupGuid, fileList) {
    var data = getUploadFileData();
    data.lastgroupguid = groupGuid;
    data.lastfilelist = fileList;
    setLocalData(uploadFileDataID, JSON.stringify(data));
}

function getUploadFileData() {
    var data = JSON.parse(getLocalData(uploadFileDataID));
    if (data == null) {
        data = {
            "lastgroupguid": "",
            "lastfilelist": [],
            "userguid": getNewGuid()
        };
        setLocalData(uploadFileDataID, JSON.stringify(data));
    }
    return data;
}

function clearLastGroupGuid() {
    var data = getUploadFileData();
    data.lastgroupguid = "";
    data.lastfilelist = [];
    setLocalData(uploadFileDataID, JSON.stringify(data));
}

function getWebsiteUserGuid() {
    var data = getUploadFileData();
    return data.userguid;
}

//价格计算部分
function caculatePrintPrice(sides, pageNum, copies) {
    var singleprice = 0;
    if (sides == "1") {
        //单面
        singleprice = 0.2;
    } else {
        //双面
        singleprice = 0.3;
    }
    return parseFloat((singleprice * pageNum * copies).toFixed(1))
}


function getDatetime() {
    var now = new Date();
    var year = now.getFullYear();       
    var month = now.getMonth() + 1;     
    var day = now.getDate();            
    var hh = now.getHours();            
    var mm = now.getMinutes();          
    var ss = now.getSeconds();          
    var clock = year + "-";
    if (month < 10)
        clock += "0";
    clock += month + "-";
    if (day < 10)
        clock += "0";
    clock += day + " ";
    if (hh < 10)
        clock += "0";
    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm + ":";
    if (ss < 10) clock += '0';
    clock += ss;
    return clock;
}